<template>
  <van-form ref="formRef" class="flex flex-col items-center" @submit="onSubmit">
    <van-field v-model="formData.account" class="enter-y mb-4 items-center !rounded-md" name="account"
      placeholder="请输入礼品册编码" :rules="getFormRules.account">
      <template #left-icon>
        <i class="i-ph:user-bold mr-2 text-lg" />
      </template>
    </van-field>
    <van-field v-model="formData.password" class="enter-y mb-3 items-center !rounded-md"
      :type="switchPassType ? 'password' : 'text'" name="password" placeholder="请输入礼品册兑换码"
      :rules="getFormRules.password" @click-right-icon="switchPassType = !switchPassType">
      <template #left-icon>
        <i class="i-iconamoon:lock-bold mr-2 text-lg" />
      </template>
      <template #right-icon>
        <i v-if="switchPassType" class="i-mdi:eye-outline mr-2 text-lg" />
        <i v-else class="i-mdi:eye-off mr-2 text-lg" />
      </template>
    </van-field>

    <view class="error_tip">
      {{error}}
    </view>

    <van-button class="login-btn enter-y !mb-4 !rounded-md" type="primary" block native-type="submit">
      登 录
    </van-button>


    <van-overlay :show="isshow" z-index="999">
      <van-loading size="24px" vertical style="top: 50%;display: flex;align-items: center;justify-content: center;" >登录中...</van-loading>
    </van-overlay>

  </van-form>
</template>

<script setup name="LoginForm">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { setToken, removeToken } from '@/utils/token-util.js';
import { CommonApi } from '@/api/CommonApi';
import { showToast } from 'vant';

const $router = useRouter();

// formData
const formData = ref({
  account: '',
  password: '',
});

// isshow
const isshow = ref(false);

// error
const error = ref('');

// getFormRules
const getFormRules = {
  account: [
    { required: true, message: '请输入用户名' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符' },
  ],
  password: [
    { required: true, message: '请输入密码' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符' },
  ],
};


// 提交
const onSubmit = () => {
  isshow.value = true;
  console.log('submit',formData.value);
  // 清空token
  removeToken();
  CommonApi.login(formData.value)
    .then(response => {
      // 没开启单点登录
      // 登录成功
      // showToast({ type: 'success', message: '登录成功' });
      setToken(response?.data?.token, true);
      // 跳转到 gift
      $router.push('/gift');
    }).catch(err => {
      console.log('err',err);
      error.value = err?.message;
      isshow.value = false;
    }).finally(() => {
      isshow.value = false;
    });
};



</script>

<style scoped>

.login-btn {
  background: #B00D0D;
  border-color: #B00D0D;
  font-size: 1.1rem;
}

.error_tip {
  color: #B00D0D;
  font-size: 0.9rem;
  margin-bottom: 1rem;
}

</style>
